<template>
	<view class="pagebg">
		<view id="container" class="bmap"></view>
		<view class="vr-box">
			<swiper :indicator-dots="false" class="swiper" v-if="currentMapRoute == 'all'">
				<swiper-item class="item" v-for="item in markers">
					<image :src="item.imgSrc" style="width: 180rpx; height: 180rpx;border-radius: 12rpx;"></image>
					<view class="title-box">
						<view class="title">{{item.title}}</view>
						<view class="des">{{item.address}}</view>
					</view>
				</swiper-item>
			</swiper>
			<swiper :indicator-dots="false" class="swiper" v-if="currentMapRoute != 'all'">
				<swiper-item class="item" v-for="item in markers.filter(j=>j.routeType == 'route'+currentMapRoute)">
					<image :src="item.imgSrc" style="width: 180rpx; height: 180rpx;border-radius: 12rpx;"></image>
					<view class="title-box">
						<view class="title">{{item.title}}</view>
						<view class="des">{{item.address}}</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="route-box">
			<view :class="currentMapRoute == item.key ? 'item active' : 'item'" v-for="(item,index) in mapRoute"
				@click="handleMapRoute(item)">
				<image v-if="index == 0 && currentMapRoute != item.key" src="../../static/route-icon.png"
					style="width: 30rpx; height: 30rpx;margin-right: 6rpx;"></image>
				<image v-if="index == 0 && currentMapRoute == item.key" src="../../static/route-icon-active.png"
					style="width: 30rpx; height: 30rpx;margin-right: 6rpx;"></image>
				{{item.label}}
			</view>
		</view>

		<view class="popup-box">
			<up-popup :show="popupShow" @close="()=>{popupShow = false; currentClick = {}}">
				<view>
					<view class="info-box">
						<image :src="currentClick.imgSrc"
							style="width: 180rpx; height: 180rpx;border-radius: 12rpx;"></image>
						<view class="title-box">
							<view class="title">{{currentClick.title}}</view>
							<view class="des">{{currentClick.address}}</view>
						</view>
					</view>
					<view class="btn-box">
						<view class="item" @click="handleWatchVR(currentClick)">
							<image src="../../static/vr-icon.png" style="width: 30rpx; height: 30rpx;margin-right: 6rpx;"></image>
							云参观
						</view>
						<view class="item" @click="handleWatchNavVR(currentClick)">
							<image src="../../static/nav-icon.png" style="width: 30rpx; height: 30rpx;margin-right: 6rpx;"></image>
							导航到这里
						</view>
					</view>
				</view>
			</up-popup>
		</view>
		
		<confirmModal :show="modalShow" title="提示" describe="暂无介绍" @close="modalShow = false"
			@confirm="handleModalChange">
		</confirmModal>
	</view>
</template>

<script setup>
	import tabbarVue from '@/components/tabbar/index.vue'
	import {
		loadJScript,
		createDOM
	} from '@/utils/BMapGL.js'
	import {
		ref,
	} from 'vue'
	import {
		onShow,
		onLoad,
		onShareAppMessage,
		onShareTimeline,
	} from '@dcloudio/uni-app'
	import baseData from '@/common/baseData.config.js'
	import {
		wxShare
	} from '@/common/api/common.js'
	import wx from 'weixin-js-sdk';
	import confirmModal from '@/components/confirmModal/index.vue'
	
	const modalShow = ref(false)

	const configInfo = ref({
		shareTitle: '江苏社科知识之旅',
		shareDetails: '江苏省社科普及基地研学游路线百度地图线上推介',
		sharePath: 'http://ditu.quanjing.tv',
		sharePicture: 'http://ditu.quanjing.tv/static/shareImg.jpg'
	})

	const ak = ref('tk1c97qBl7PegAOyBk7UHbNQe97a2n4k')
	const map = ref(null)
	const markers = ref([])
	const zoom = ref(8)

	const popupShow = ref(false)
	const currentClick = ref({})

	const mapRoute = ref([{
		key: 'all',
		label: '全部'
	}, {
		key: 1,
		label: '传承红色基因'
	}, {
		key: 2,
		label: '非遗文化“活起来”'
	}, {
		key: 3,
		label: '探访特色打卡地'
	}])
	const currentMapRoute = ref('all')

	const showInfo = ref({})
	
	const handleModalChange = () => {
		console.log(111)
		modalShow.value = false
	}

	const initBaiduMap = async () => {
		loadJScript(ak.value).then(async mymap => {
			map.value = new BMapGL.Map('container'); // 创建Map实例
			const point = new BMapGL.Point(118.817846, 32.102999)
			// map.value.centerAndZoom(point, 8); // 初始化地图,设置中心点坐标和地图级别
			map.value.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放

			map.value.setMapStyleV2({
				styleId: '9ec69527b5e4d918b15a98147ff7632a'
			});

			// 创建省界查询实例
			let bdary = new BMapGL.Boundary();
			// 查询省份边界
			bdary.get("江苏省", function(rs) { //获取行政区域
				if (rs?.boundaries?.length > 0) {
					// 画出省界
					rs.boundaries.map(item => {
						let point = []
						item.split(';').map(item => {
							point.push(new BMapGL.Point(Number(item.split(',')[0]), Number(item.split(',')[1])))
						})
						var ply = new BMapGL.Polyline(point, {
							strokeColor: "blue",
							strokeWeight: 2,
							strokeOpacity: 0.5
						});
						map.value.addOverlay(ply); //添加Overlay
						map.value.setViewport(ply.getPath()); //调整视野
					})
				}
			});

			addMarkers('all')

			map.value.addEventListener("zooming", function() {
				// 获取当前地图级别
				var zoomLevel = map.value.getZoom();
				// console.log("当前地图级别: " + zoomLevel);

				loopMarker(zoomLevel)

			})

		})
	}

	const loopMarker = (zoomLevel) => {
		var markerBoxs = document.getElementsByClassName("marker-box");

		// 遍历这些元素
		for (let i = 0; i < markerBoxs.length; i++) {
			let flag = false

			let markerBoxs1 = document.getElementsByClassName("marker-box");
			// console.log(markerBoxs.length,markerBoxs1.findIndex(item=>item.style.width == '6px'))
			for (let j = 0; j < markerBoxs1.length; j++) {

				if (markerBoxs1[j].style.width != '6px' && markerBoxs1[j].style.display != 'none') {
					if (markerBoxs[i] != markerBoxs1[j]) {
						if (isDivOverlapping(markerBoxs[i], markerBoxs1[j])) {
							flag = true
						}
					}
				}

				if (j + 1 == markerBoxs1.length) {
					if (flag) {
						if (zoomLevel < zoom.value) {
							markerBoxs[i].style.opacity = '100'
							const children = markerBoxs[i].querySelectorAll('*');
							children.forEach((child) => {
								if (child.className == 'marker-title') {
									child.style.opacity = '0'; // 隐藏每一个子元素
								} else {
									child.style.display = 'none'; // 隐藏每一个子元素
								}
							});
							markerBoxs[i].style.width = '6px'
							markerBoxs[i].style.height = '6px'
							markerBoxs[i].style.zIndex = '999'
						}
					} else {
						if (zoomLevel > zoom.value) {
							showMarkerBox(markerBoxs[i])
						}
					}
				}
			}

		}

		var markerTitle = document.getElementsByClassName("marker-title");
		for (let i = 0; i < markerTitle.length; i++) {
			let flag = false

			let markerTitle1 = document.getElementsByClassName("marker-title");
			for (let j = 0; j < markerTitle1.length; j++) {
				// console.log(markerTitle1[j].style.opacity,1222222)
				if (markerTitle1[j].style.opacity != '0') {
					if (markerTitle[i] != markerTitle1[j]) {
						if (isDivOverlapping(markerTitle[i], markerTitle1[j])) {
							flag = true
						}
					}
				}
				if (j + 1 == markerTitle1.length) {
					if (flag) {
						if (zoomLevel < zoom.value) {
							markerTitle[i].style.opacity = '0'
						}
					} else {
						if (zoomLevel > zoom.value) {
							let parentDiv = markerTitle[i].parentNode;
							if (parentDiv.style.width != '6px') {
								markerTitle[i].style.opacity = '100'
								markerTitle[i].style.zIndex = '999'
							}
						}
					}

				}
			}

		}

		zoom.value = zoomLevel
	}

	const handleMapRoute = (e) => {
		// map.value.clearOverlays();
		currentMapRoute.value = e.key

		var elements1 = document.getElementsByClassName("route1");
		var elements2 = document.getElementsByClassName("route2");
		var elements3 = document.getElementsByClassName("route3");

		// 遍历这些元素
		for (var i = 0; i < elements1.length; i++) {
			if (e.key == 1 || e.key == 'all') {
				elements1[i].style.display = 'flex'
				// showMarkerBox(elements1[i])
			} else {
				elements1[i].style.display = 'none'
			}
		}

		// 遍历这些元素
		for (var i = 0; i < elements2.length; i++) {
			if (e.key == 2 || e.key == 'all') {
				elements2[i].style.display = 'flex'
				// showMarkerBox(elements2[i])
			} else {
				elements2[i].style.display = 'none'
			}
		}

		// 遍历这些元素
		for (var i = 0; i < elements3.length; i++) {
			if (e.key == 3 || e.key == 'all') {
				elements3[i].style.display = 'flex'
				// showMarkerBox(elements3[i])
			} else {
				elements3[i].style.display = 'none'
			}
		}

		const currentZoom = map.value.getZoom();
		if(e.key == 'all'){
			map.value.setZoom(currentZoom - 0.01)
		}else{
			map.value.setZoom(currentZoom + 0.1)
			setTimeout(()=>{
				map.value.setZoom(currentZoom - 0.01)
			},100)
			
		}

		// loopMarker(currentZoom - 0.000000000000002)
	}

	const showMarkerBox = (dom) => {
		dom.style.opacity = '100'
		const children = dom.querySelectorAll('*');
		children.forEach(function(child) {
			if (child.className != 'marker-title') {
				child.style.display = 'block'; // 隐藏每一个子元素
			}
		});
		dom.style.width = '30px'
		dom.style.height = '30px'
		dom.style.zIndex = '99'
	}


	const isDivOverlapping = (div1, div2) => {
		var rect1 = div1.getBoundingClientRect();
		var rect2 = div2.getBoundingClientRect();
		// console.log(rect1.right, rect2.left,2222222)
		if (rect1.left == 0 && rect2.left == 0) {
			return false;
		}

		return !(rect1.right < rect2.left ||
			rect1.left > rect2.right ||
			rect1.bottom < rect2.top ||
			rect1.top > rect2.bottom);
	}

	const addMarkers = (type) => {
		// 创建标注点集合
		var markerClusterer = null;
		if (type == 'all') {
			markers.value.map((item, index) => {
				addOverlay(item, index)
			})
		}
		if (type != 'all') {
			markers.value.map((item, index) => {
				if (item.routeType == 'route' + type) {
					addOverlay(item, index)
				}
			})
		}
	}

	const addOverlay = (data, index) => {
		// 创建自定义覆盖物
		let customOverlay = new BMapGL.CustomOverlay(createDOM, {
			point: new BMapGL.Point(data.point.lng, data.point.lat),
			// opacity: 0.5,
			// offsetY: -32,
			properties: {
				title: data.title,
				imgSrc: data.imgSrc,
				bgColor: data.bgColor,
				routeType: data.routeType,
				address: data.address,
				pagePath: data.pagePath,
				point: new BMapGL.Point(data.point.lng, data.point.lat),
				index: index
			}
		});
		map.value.addOverlay(customOverlay);
		customOverlay.addEventListener('click', (e) => {
			// console.log(e)
			// //点击后执行的code
			// let data = e.target.properties.title;
			// uni.navigateTo({
			// 	url: '/pages/webview/webview?url=' + decodeURIComponent(data.pagePath) + '&title=' + e.target
			// 		.properties.title
			// })
			currentClick.value = e.target.properties
			popupShow.value = true
		});
	}



	const handleWatchVR = (data) => {
		if(!data.pagePath){
			modalShow.value = true
			return;
		}
		uni.navigateTo({
			url: '/pages/webview/webview?url=' + decodeURIComponent(data.pagePath) + '&title=' + data.title
		})
	}

	const handleWatchNavVR = (data) => {
		console.log(data)
		const url =
			`http://api.map.baidu.com/marker?location=${data.point.lat},${data.point.lng}&title=${data.title}&content=${data.address}&output=html`
		window.location.href = url;
	}

	const wxShareFn = async () => {
		const res = await wxShare()
		if (res.code == 0) {
			showInfo.value = res.data

			wx.config({
				debug: false, // 开启调试模式
				appId: showInfo.value.appId,
				timestamp: showInfo.value.timestamp,
				nonceStr: showInfo.value.nonceStr,
				signature: showInfo.value.signature,
				jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
			});

			setTimeout(() => {
				wx.ready(() => {
					//自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
					wx.onMenuShareAppMessage({
						title: configInfo.value.shareTitle,
						desc: configInfo.value.shareDetails,
						link: configInfo.value.sharePath,
						imgUrl: configInfo.value.sharePicture,
						success: res => {

						},
						cancel: function() {
							// 用户取消分享后执行的回调函数
						}
					})
					//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
					wx.onMenuShareTimeline({
						title: configInfo.value.shareTitle,
						desc: configInfo.value.shareDetails,
						link: configInfo.value.sharePath,
						imgUrl: configInfo.value.sharePicture,
						success: res => {

						},
						cancel: function() {
							// 用户取消分享后执行的回调函数
						}
					})
				})
			}, 500)

		}
	}

	onLoad(() => {
		initBaiduMap();
	})
	onShow(() => {
		markers.value = baseData.route
		wxShareFn()
	})
</script>

<style>
	page {
		background: #ffffff;
	}
</style>
<style lang="scss" scoped>
	.bmap {
		width: 100vw;
		// height: calc(100vh - 110rpx - env(safe-area-inset-bottom));
		height: 100vh;
	}

	.vr-box {
		display: none;
		width: 100vw;
		height: 270rpx;
		position: fixed;
		bottom: calc(110rpx + env(safe-area-inset-bottom));
		background-color: #ffffff;
		z-index: 99;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		padding: 40rpx;
		box-sizing: border-box;

		.swiper {
			height: 200rpx;
		}

		.item {
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.title-box {
				padding-left: 20rpx;

				.title {
					font-size: 32rpx;
					font-weight: 500;
					margin-bottom: 10rpx;
				}

				.des {
					color: #999;
				}
			}
		}


	}


	.route-box {
		position: fixed;
		bottom: env(safe-area-inset-bottom);
		right: 0;
		z-index: 99;
		width: 160px;
		// height: calc(110rpx + env(safe-area-inset-bottom));
		display: flex;
		// justify-content: space-between;
		flex-direction: column;
		padding: 20rpx 20rpx 0;
		box-sizing: border-box;
		// background-color: #f5f5f5;

		.item {
			padding: 0 14rpx;
			height: 70rpx;
			background-color: #ffffff;
			border-radius: 44rpx;
			line-height: 70rpx;
			text-align: center;
			font-size: 24rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10rpx;
			box-shadow: 0 0 10px rgba(218, 168, 183, 0.2), 0 0 10px rgba(218, 168, 183, 0.4), 0 0 10px rgba(218, 168, 183, 0.2);
		}

		.active {
			background-color: #1890ff;
			color: #ffffff;
		}
	}

	.popup-box {
		::v-deep .u-popup__content {
			padding: 40rpx;
			box-sizing: border-box;
			height: 200px;
			border-top-left-radius: 0.9375rem;
			border-top-right-radius: 0.9375rem;
		}

		.info-box {
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.title-box {
				padding-left: 20rpx;

				.title {
					font-size: 32rpx;
					font-weight: 500;
					margin-bottom: 10rpx;
				}

				.des {
					color: #999;
				}
			}
		}

		.btn-box {
			width: calc(100vw - 80rpx);
			height: calc(110rpx + env(safe-area-inset-bottom));
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0 0;
			box-sizing: border-box;

			.item {
				width: calc(50% - 20rpx);
				height: 70rpx;
				background-color: #f5f5f5;
				border-radius: 44rpx;
				line-height: 70rpx;
				text-align: center;
				font-size: 30rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>